/**
 * @param { url } 接口地址
 * @param { method } 请求方式
 * @param { data } 请求参数
 * @param { header } 请求头/token/cookie
 * @param { hideLoading }  显示加载动画
 * @dataType 解析为JSON
 */
type ENUM_METHOD = "GET"|"POST"|"DELETE"|"PUT"
type Options_Type = {
	url: string
	method: ENUM_METHOD
	data?: any
	header?: any
	hideLoading?: boolean
}
let BASE_URL = ''
if(!alert){
	BASE_URL = 'http://localhost:19999' 
}else {
	BASE_URL = '/api'
}
const request = (options: Options_Type) => {
	let hideLoading = options.hideLoading || true
	if(!hideLoading) {
		uni.showLoading({
			title: "Loading"
		})
	}
	const {token} = uni.getStorageSync('userInfo')
	if(!token) {
		uni.redirectTo({
			url: "/pages/login/index"
		})
	}
	// 'content-Type': 'application/json;charset=UTF-8',
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || "GET",
			header: {
				...options.header,
				Authorization: token ?? ''
			},
			dataType:'json',
			data: {
				...options.data,
			} || {},
			success: (res) => {
				if(res?.data?.code === "0" || res?.data?.success) {
					resolve(res.data)
				} else {
					uni.showToast({
						icon: "error",
						title: res?.data?.message
					})
					reject(res?.data)
				}
			},
			fail: (err) => {
				reject(err)
			},
			complete: () => {
				if(!hideLoading) {
					uni.hideLoading()
				}
				return
			}
		})
	})
}

export {
	request
}